<template>
  <!-- 发现新版本对话框 -->
  <el-dialog
    v-model="showUpdateDialog"
    title="发现新版本"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="update-info">
      <div class="version-info">
        <p><strong>新版本：</strong>{{ updateInfo.version }}</p>
        <p><strong>发布日期：</strong>{{ formatDate(updateInfo.releaseDate) }}</p>
        <p><strong>文件大小：</strong>{{ formatFileSize(updateInfo.files?.[0]?.size || 0) }}</p>
      </div>

      <div class="release-notes" v-if="updateInfo.releaseNotes">
        <h4>更新内容：</h4>
        <div class="notes-content" v-html="updateInfo.releaseNotes"></div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="skipUpdate">跳过此版本</el-button>
        <el-button @click="remindLater">稍后提醒</el-button>
        <el-button type="primary" @click="startDownload">立即更新</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 下载更新对话框 -->
  <el-dialog
    v-model="showDownloadDialog"
    title="下载更新"
    width="450px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="download-progress">
      <el-progress :percentage="downloadProgress.percent" :stroke-width="8" status="success" />

      <div class="progress-info">
        <p>下载速度: {{ formatSpeed(downloadProgress.bytesPerSecond) }}</p>
        <p>
          已下载: {{ formatFileSize(downloadProgress.transferred) }} /
          {{ formatFileSize(downloadProgress.total) }}
        </p>
      </div>
    </div>
  </el-dialog>

  <!-- 更新已下载对话框 -->
  <el-dialog
    v-model="showInstallDialog"
    title="更新已下载"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="install-info">
      <p>新版本已下载完成，是否立即重启应用进行安装？</p>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="installLater">稍后安装</el-button>
        <el-button type="primary" @click="installNow">立即安装</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 更新失败对话框 -->
  <el-dialog
    v-model="showErrorDialog"
    title="更新失败"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="error-info">
      <p>{{ errorMessage }}</p>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeError">关闭</el-button>
        <el-button type="primary" @click="retryUpdate">重试</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式状态
const updateStatus = ref('idle') // idle, checking, available, downloading, downloaded, error
const showUpdateDialog = ref(false)
const showDownloadDialog = ref(false)
const showInstallDialog = ref(false)
const showErrorDialog = ref(false)

// 更新信息
const updateInfo = reactive({
  version: '',
  releaseDate: '',
  releaseNotes: '',
  files: []
})

// 下载进度
const downloadProgress = reactive({
  percent: 0,
  bytesPerSecond: 0,
  transferred: 0,
  total: 0
})

// 错误信息
const errorMessage = ref('')

// 更新器消息监听器
let removeListener = null

// 处理更新器消息
const handleUpdaterMessage = message => {
  console.log('收到更新消息:', message)

  switch (message.type) {
    case 'update-checking':
      updateStatus.value = 'checking'
      ElMessage.info('正在检查更新...')
      break

    case 'update-available':
      updateStatus.value = 'available'
      Object.assign(updateInfo, message.data)
      showUpdateDialog.value = true
      break

    case 'update-not-available':
      updateStatus.value = 'idle'
      ElMessage.success('当前已是最新版本')
      break

    case 'download-progress':
      updateStatus.value = 'downloading'
      Object.assign(downloadProgress, message.data)
      if (!showDownloadDialog.value) {
        showDownloadDialog.value = true
      }
      break

    case 'update-downloaded':
      updateStatus.value = 'downloaded'
      showDownloadDialog.value = false
      showInstallDialog.value = true
      break

    case 'update-error':
      updateStatus.value = 'error'
      errorMessage.value = message.data.message || '更新过程中发生未知错误'
      showDownloadDialog.value = false
      showErrorDialog.value = true
      break
  }
}

// 用户操作处理
const startDownload = () => {
  showUpdateDialog.value = false
  window.electronAPI.updater.downloadUpdate()
}

const skipUpdate = () => {
  showUpdateDialog.value = false
  updateStatus.value = 'idle'
}

const remindLater = () => {
  showUpdateDialog.value = false
  updateStatus.value = 'idle'
  ElMessage.info('将在下次启动时提醒您更新')
}

const installNow = () => {
  showInstallDialog.value = false
  window.electronAPI.updater.installUpdate()
}

const installLater = () => {
  showInstallDialog.value = false
  updateStatus.value = 'idle'
  ElMessage.info('更新包已保存，您可以稍后手动安装')
}

const closeError = () => {
  showErrorDialog.value = false
  updateStatus.value = 'idle'
}

const retryUpdate = () => {
  showErrorDialog.value = false
  updateStatus.value = 'idle'
  setTimeout(() => {
    window.electronAPI.updater.checkForUpdates()
  }, 1000)
}

// 工具函数
const formatDate = dateString => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatFileSize = bytes => {
  if (!bytes) return '0 B'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i]
}

const formatSpeed = bytesPerSecond => {
  return formatFileSize(bytesPerSecond) + '/s'
}

// 手动检查更新
const checkForUpdates = () => {
  if (updateStatus.value === 'checking') {
    ElMessage.warning('正在检查更新，请稍候...')
    return
  }
  window.electronAPI.updater.checkForUpdates()
}

// 生命周期钩子
onMounted(() => {
  if (window.electronAPI?.updater) {
    removeListener = window.electronAPI.updater.onMessage(handleUpdaterMessage)
  }
})

onUnmounted(() => {
  if (removeListener) {
    removeListener()
  }
})

// 暴露方法给父组件
defineExpose({
  checkForUpdates
})
</script>

<style scoped>
.update-info {
  padding: 10px 0;
}

.version-info {
  margin-bottom: 20px;
}

.version-info p {
  margin: 8px 0;
  color: #606266;
}

.release-notes {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.release-notes h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.notes-content {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
  line-height: 1.6;
  color: #606266;
}

.download-progress {
  padding: 20px 0;
}

.progress-info {
  margin-top: 15px;
  text-align: center;
}

.progress-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
}

.install-info {
  padding: 20px 0;
  text-align: center;
}

.install-info p {
  color: #606266;
  line-height: 1.6;
}

.error-info {
  padding: 20px 0;
  text-align: center;
}

.error-info p {
  color: #f56c6c;
  line-height: 1.6;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>
